package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constants.AvatarMessageConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.CluDO;
import com.qk.domain.clue.ClueDO;
import com.qk.dto.clue.ClueDTO;
import com.qk.dto.clue.ClueListDTO;
import com.qk.dto.clue.UpdateClueInfoDTO;
import com.qk.dto.clue.poolDTO;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.FakeClueDTO;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ClueMapper clueMapper;


    @Override
    @Transactional
    public PageResult<CluDO> poolCluelsit(poolDTO dto) {
        Page<CluDO> page = new Page<>(dto.getPage(),dto.getPageSize());
        List<CluDO> result = clueMapper.selectPool(dto);
        page.setTotal(result.size());
        page.setRecords(result);
        return PageResult.<CluDO>builder()
                .total(page.getTotal())
                .rows(page.getRecords())
                .build();
    }

    @Transactional
    @Override
    public void setClueToFake(FakeClueDTO dto) {
        try {
            Integer id = dto.getId();
            if (ObjectUtil.isNull(id)) {
                log.error("伪线索上报失败，线索ID为空");
                CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
            }

            Clue clue = this.baseMapper.selectById(id);
            if (ObjectUtil.isNull(clue)) {
                log.error("伪线索上报失败，线索不存在，ID:{}", id);
                CommonException.throwCommonException(ParamEnum.CLUE_NOT_EXIST_OR_DELETED);
            }

            clue.setStatus(AvatarMessageConstants.WAIT_PSEUDO);
            clue.setUpdateTime(LocalDateTime.now());
            this.baseMapper.updateById(clue);
            ClueTrackRecord trackRecord = new ClueTrackRecord();
            trackRecord.setClueId(id);
            trackRecord.setCreateTime(LocalDateTime.now());
            trackRecord.setType(0);
            trackRecord.setUserId(CurrentUserContextHolders.get());
            String reasonStr = dto.getReason();
            if (ObjectUtil.isNotEmpty(reasonStr)) {
                try {
                    trackRecord.setFalseReason(Integer.valueOf(reasonStr));
                } catch (NumberFormatException e) {
                    log.warn("伪线索原因转换失败，使用默认值: {}", reasonStr);
                    trackRecord.setFalseReason(0);
                }
            } else {
                trackRecord.setFalseReason(0);
            }
            this.clueTrackRecordMapper.insert(trackRecord);

            log.info("伪线索上报成功，线索ID:{}，原因:{}", id, reasonStr);

        } catch (CommonException e) {
            throw e;
        } catch (Exception e) {
            log.error("伪线索上报发生系统异常", e);
            throw new CommonException(ParamEnum.PARAM_ERROR);
        }
    }

    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(AvatarMessageConstants.CONVERT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(AvatarMessageConstants.WAIT_ALLOCATION);
        business.setClueId(id);
        this.businessMapper.insert(business);
    }

    @Transactional
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if (dto.getStatus() == AvatarMessageConstants.WAIT_FOLLOW_UP) {
            clue.setStatus(AvatarMessageConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(AvatarMessageConstants.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        Integer userId = clue.getUserId();
        User user = userMapper.selectById(userId);
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.
                selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id)
        );
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }

    public PageResult<ClueDO> clueListMp(ClueListDTO dto) {
        Page pages = new Page<>(dto.getPage(), dto.getPageSize());
        Page<ClueDO> clueDOPage = this.baseMapper.selectByPageMp(pages, dto);
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(clueDOPage.getTotal()).intValue())
                .rows(clueDOPage.getRecords())
                .build();
    }

    @Override
    public void addClue(ClueDTO dto) {
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(AvatarMessageConstants.WAIT_ALLOCATION);
        this.save(clue);
    }
}